package utils;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelWriter {

	private Workbook workbook;

	private Sheet sheet;

	private Map<Integer, Row> rows = new HashMap<>();
	
	public ExcelWriter() {
		this.workbook = new XSSFWorkbook();
		this.sheet = workbook.createSheet("学生成绩");
	}
	
	public void write(int r, int c, String value) {

		Row row = rows.get(r);
		if (row == null) {
			row = sheet.createRow(r);
			rows.put(r, row);
		}

		Cell cell = row.createCell(c);
		cell.setCellType(CellType.STRING);
		cell.setCellValue(value);
	}
	

	public boolean saveToFile(OutputStream out) {
		try {
			workbook.write(out);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public void close() throws IOException {
		this.workbook.close();
	}
}
